package com.zline.foodraise.ui.activity;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.CustomerFragmentAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.OrderManagerFragmentListener;
import com.zline.foodraise.ui.fragment.AllOrdersFragment;
import com.zline.foodraise.ui.fragment.AllOrdersFragment_;
import com.zline.foodraise.ui.fragment.DeliveryHomeFragment;
import com.zline.foodraise.ui.fragment.DeliveryHomeFragment_;
import com.zline.foodraise.ui.fragment.EatFragment;
import com.zline.foodraise.ui.fragment.StoreEatFragment;
import com.zline.foodraise.ui.fragment.StoreEatFragment_;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.view.WrapContentViewPager;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by heshantao on 15/12/25.
 * 众筹订单管理
 */
@EActivity(R.layout.activity_project_order_manager)
public class ProjectOrderManagerActivity extends ZlineActivity implements OrderManagerFragmentListener{
    private static final String LOG_TAG = ProjectOrderManagerActivity.class.getSimpleName();
    @ViewById(R.id.project_order_manager_tl)
    TabLayout tabLayout;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    CustomerFragmentAdapter fragmentAdapter;
    FragmentManager fManager;
    AllOrdersFragment allOrdersFragment;
    StoreEatFragment storeEatFragment;
    DeliveryHomeFragment deliveryHomeFragment;
    ArrayList<Fragment> fragments;
    //已付款
    @ViewById(R.id.order_payed)
    TextView bottom1_tv;
    //待处理Relativelayout
    @ViewById(R.id.order_unHandle_rl)
    RelativeLayout bottom2_rl;
    @ViewById(R.id.order_unHandle_red_point)
    View unHandler_red_point;
    //已处理
    @ViewById(R.id.order_handled)
    TextView bottom3_tv;
    //无效单
    @ViewById(R.id.order_invalid)
    TextView bottom4_tv;
    @ViewById(R.id.project_order_manager_vg)
    WrapContentViewPager viewPager;
    //底部已付款等tab选中标示
    @Extra
    int lastTab;
    //项目Id
    @Extra
    long projectId;
    //项目名称
    @Extra
    String projectName;
    //是否是所有众筹项目的订单
    @Extra
    boolean allProjectOrder;
    @Pref
    AppPref_ appPref;
    long userId;
    @Bean
    HttpUtil httpUtil;
    @Bean
    HttpOperator httpOperator;
    int resultCode = 0;
    int totle_unHandler_order;

    @AfterViews
    void doSomeAfterView() {
        userId = appPref.userId().get();
        initView();
        requestUnHandlerOrder();
    }

    void initView() {
        title_tv.setText(projectName);
        initTablayout();
        selectedBottomTab(lastTab);
    }


    //请求是否有未处理订单
    void requestUnHandlerOrder() {
        if (allProjectOrder) {
            httpOperator.requestUserProjectOrderList(httpUtil, userId, 0, 2,
                    1, 1, requestProjectOrderListHandler);
        } else {
            httpOperator.requestProjectOrderList(httpUtil, projectId, 0, 2,
                    1, 1, requestProjectOrderListHandler);
        }
    }


    //获取筹未处理订单列表回调
    AsyncHttpResponseHandler requestProjectOrderListHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestProjectOrderListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        getUnHandlerCount(response);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };

    //获得未处理订单数量
    void getUnHandlerCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.CF_ORDER_BEAN_PAGE);
            totle_unHandler_order = jsonObject.getInt(Constant.TOTAL_COUNT);
            if(totle_unHandler_order>0){
                unHandler_red_point.setVisibility(View.VISIBLE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    void initTablayout() {
        fragments = new ArrayList<Fragment>();
        allOrdersFragment = AllOrdersFragment_.builder().
                projectId(projectId).selectStatus(lastTab + 1)
                .userId(userId).allProjectOrder(allProjectOrder).build();
        allOrdersFragment.setFragmentListener(this);
        storeEatFragment = StoreEatFragment_.builder().
                projectId(projectId).selectStatus(lastTab + 1)
                .userId(userId).allProjectOrder(allProjectOrder).build();
        storeEatFragment.setFragmentListener(this);
        deliveryHomeFragment = DeliveryHomeFragment_.builder().
                projectId(projectId).selectStatus(lastTab + 1)
                .userId(userId).allProjectOrder(allProjectOrder).build();
        deliveryHomeFragment.setFragmentListener(this);
        fragments.add(allOrdersFragment);
        fragments.add(storeEatFragment);
        fragments.add(deliveryHomeFragment);
        fManager = getSupportFragmentManager();
        fragmentAdapter = new CustomerFragmentAdapter(fManager);
        fragmentAdapter.setFragments(fragments);
        viewPager.setAdapter(fragmentAdapter);
        viewPager.setOffscreenPageLimit(2);//设置ViewPager缓存页面
        tabLayout.addTab(tabLayout.newTab().setText(R.string.orders_all));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.orders_eat_in_store));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.orders_delivery_home));
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                changeBottomTab(lastTab);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }


    //将其他底部tab 设置为未选中状态
    void unSelectBottomTab(int index) {
        switch (index) {
            case 0:
                bottom1_tv.setSelected(false);
                break;
            case 1:
                bottom2_rl.setSelected(false);
                break;
            case 2:
                bottom3_tv.setSelected(false);
                break;
            case 3:
                bottom4_tv.setSelected(false);
                break;
            default:
                break;
        }
    }

    //底部状态选中
    void selectedBottomTab(int index) {
        switch (index) {
            case 0:
                bottom1_tv.setSelected(true);
                break;
            case 1:
                bottom2_rl.setSelected(true);
                break;
            case 2:
                bottom3_tv.setSelected(true);
                break;
            case 3:
                bottom4_tv.setSelected(true);
                break;
            default:
                break;
        }
    }

    //底部状态栏的改变
    void changeBottomTab(int currentTab) {
        unSelectBottomTab(lastTab);
        lastTab = currentTab;
        selectedBottomTab(currentTab);
        Fragment currentFragment = fragments.get(tabLayout.getSelectedTabPosition());
        if (currentFragment instanceof AllOrdersFragment) {
            ((AllOrdersFragment) currentFragment).changeSelectStatus(currentTab);
        }
        if (currentFragment instanceof StoreEatFragment) {
            ((StoreEatFragment) currentFragment).changeSelectStatus(currentTab);
        }

        if (currentFragment instanceof DeliveryHomeFragment) {
            ((DeliveryHomeFragment) currentFragment).changeSelectStatus(currentTab);
        }
    }

    @Click({R.id.order_payed, R.id.order_unHandle
            , R.id.order_handled, R.id.order_invalid
            , R.id.app_common_header_left_icon_iv
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.order_payed:
                changeBottomTab(0);
                break;
            case R.id.order_unHandle:
                changeBottomTab(1);
                break;
            case R.id.order_handled:
                changeBottomTab(2);
                break;
            case R.id.order_invalid:
                changeBottomTab(3);
                break;
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            default:
                break;
        }
    }

    @Override
    public void hasUnHandlerOrder(boolean isHas) {
        if(isHas){
            unHandler_red_point.setVisibility(View.VISIBLE);
        }else {
            unHandler_red_point.setVisibility(View.GONE);
        }
    }
}
